let d1RowsLock = 0;
$NG.AllReady(function (page, { useValuesChange, useClick,useBeforeClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
  console.log("page is ready");
  console.log($NG.getPageUI());
  console.log($NG.getPageState());
  var mstform = $NG.getCmpApi("p_form_invoice_apply_m");
  var dgrid = $NG.getCmpApi("p_form_invoice_apply_d");

  const toolbar = $NG.getCmpApi("toolbar");
  const toolbar_top = $NG.getCmpApi("toolbar_top");
  const toolbar_dgrid1 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d");
  const toolbar_dgrid2 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d1");
  const toolbars = [
    { toolbar: toolbar_top, items: ["imp"] },
    { toolbar: toolbar_dgrid2, items: ["imp"] },
  ];
  toolbars.forEach(({ toolbar, items }) => {
    if (toolbar && typeof toolbar.getItem === "function") {
      items.forEach((item) => {
        const button = toolbar.getItem(item);
        if (button) {
          button.setHidden(); // 隐藏按钮
        }
      });
    }
  });
useBeforeClick(async ()=>{
    const rows = dgrid.getRows()
    let lock1 = true
    let lock2 = true
    for(let i =0;i<rows.length;i++){
        const item = rows[i]
        if(item.taxrate != mstform.getItem("u_kpsl").getValue()){
            lock1 = false
            break
        } 
    }
        
    // 商品名称
    let gc= true
    rows.forEach(el=>{
        if(el.u_ssfl_no == 4100){
            gc = false
        }
    })
    if(!gc){
        const shapName = rows.reduce((value,item)=>{
            value.push(item.u_product_name)
            return value
        },[])
        if(new Set(shapName).size > 1){
            lock2 = false
            $NG.alert("工程建筑类的商品名称需一致，请进行修改!")
            return lock2
        }
        
    }
    let str = ""
    if(!lock1){
        str +='开票税率与合同评审税率不一致，请修改！'
        return await $NG.confirm(str)
    } else {
        return true
    }
    },"save")
  toolbar_dgrid1.getItem("imp").setProps({ children: "引用合同清单明细" });
function hiddenKey(){
    ["u_lzfpdm", "u_lzfphm", "u_hzxx"].forEach((field) => {
        $NG.updateUI((updater) => {
            // sumAmt()
            console.log(`updater`,updater);// 删除就报错玄学
            
            updater.fieldSetForm.p_form_invoice_apply_m['发票信息'][field].setProps({
            disabled: mstform.getItem("u_hllx").getValue() === "1",
            required: ["u_lzfpdm", "u_hzxx"].includes(field)?false:!(mstform.getItem("u_hllx").getValue() === "1"),
        });
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_invoice_apply_m.u_invoice_type.setProps({
            disabled: mstform.getItem("u_hllx").getValue() == '2',
        });
    });
    // 红票只读数量
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_invoice_apply_d.qty.setProps({
          disabled: mstform.getItem("u_hllx").getValue()=='2',
      });
    });

    dgrid.getData().forEach((item) => {
        const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz","u_bybh"];
        console.log(`调试`,item.u_ssfl_no);
        if (item.u_ssfl_no == 4100) {
            if(mstform.getItem("u_hllx").getValue()=='1'){
                $NG.updateUI((updater) => {
                    fields.forEach((field) => {
                    updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                        required: true,
                        hidden: false,
                    });
                    });
                });
            }
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_invoice_apply_m.u_hbkp.setProps({
                    disabled: true,
                });
            });
            $NG.updateState((updater)=>{
                updater.data.p_form_invoice_apply_m.setProps({
                    u_hbkp:'1'
                })
            })
        } else {
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                    required: false,
                    hidden: true,
                });
                });
            });
        }
        if(mstform.getItem("u_kdbz").getValue() == '1'){
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                updater.fieldSetForm.p_form_invoice_apply_m.u_bybh.setProps({
                    required: true,
                    hidden: false,
                });
                });
            });
        } else {
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                updater.fieldSetForm.p_form_invoice_apply_m.u_bybh.setProps({
                    required: false,
                    hidden: true,
                });
                });
            });
        }
    });
}
// 过滤蓝字号码
filterMfp()
function filterMfp(){
    $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_invoice_apply_m.u_lzfphm.setProps({
          onBeforeOpen: async () => {
            var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
            console.log(`项目名：`, phid_pc);
            if (!phid_pc) {
              $NG.alert("请先选择项目");
              return false;
            } else {
              return true;
            }
          },
          ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
            clientSqlFilter: {
              'cnt.phid':$NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue(),
              'pt.phid': $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
            },
          }),
        });
      });
}

  if (mstform) {
    setTimeout(()=>{
        getSumInvInfo(mstform)
        isGcService()
        //init///////////////////////////////
        hiddenKey()
    },1000)
    page.oType == 'add'&&mstformUpdateUI(mstform);
    // getEnterpriseInfoByPhid(mstform);
    getProjectInfo(mstform);
    cntMFilter();
    if (page.oType == "add") {
      getCntCount();
    }
  }
  if (dgrid) {
    // dgrid1UpdateUI();
    cntDFilter();
  }
  //页面条件
  if (page.oType == "add" ) {
    $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, (res) => {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas);
      //   开票申请里的发票类型改为手填20241225
      //   console.log("拿去合同号带出来的发票类型", mstform.getItem("u_invoice_type"));
      //更新UI表格
      $NG.updateState((updater) => {
        //【注意这里的表名不能为控件ID，必须要是表名】
        updater.data.p_form_invoice_apply_m.setProps({

          u_dept_apply: {
            value: datas.dept_phid,
            label: datas.dept_name,
          },
        });
      });
    });
    const user = $NG.getUser()
        $NG.updateState((updater) => {
            //【注意这里的表名不能为控件ID，必须要是表名】
            updater.data.p_form_invoice_apply_m.setProps({
              u_hr_apply: {
                value: user.userID,
                label: user.userName,
              },
              u_dept_apply: {
                value: user.userID,
                label: user.userName,
              },
            });
          });
    calculationPay();
  }
  function init() {
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_invoice_dt: formatDate(new Date(), "yyyy-mm-dd"),
      });
    });
  }
  useValuesChange(({args})=>{
    console.log(`监听成功`,);
    hiddenKey()
},"p_form_invoice_apply_m.u_kdbz")

    useValuesChange(({args})=>{
        console.log(`蓝字发票监听`,args);
        getLzfpInfo()
        $NG.updateState((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_lzfpdm:args[0].u_lzfphm.origin.u_fpdm
            })
        })
    },"p_form_invoice_apply_m.u_lzfphm")

  // 监听字段项目
  useValuesChange(({ args }) => {
    console.log(`监听项目字段`, args);
    cntMFilter();
    getCntCount();
    getProjectInfo(mstform);
    getLcbHkInfo()
    getSumInvInfo(mstform)
    filterMfp()
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_cnt: {
          label: null,
          value: null,
        },
        u_cnt_no: null,
        u_cnt_amt: null,
      });
    });
  }, "p_form_invoice_apply_m.phid_pc");

  //表头字段变化逻辑BEGIN
  useValuesChange(({ args }) => {
    getCntMInfoByPhid();
    getXsCntskInfo()
    getProjectInAmtInfo()
    getKpinfoTotalAmt()
    cntDFilter();
    filterMfp()
  }, "p_form_invoice_apply_m.u_cnt");

  //监听汇款差额
  useValuesChange(({ args }) => {
    const _data = args[0].u_hkkpce;

    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: true, //必输
        });
      } else {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: false, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_hkkpce");

  useValuesChange(({ args }) => {
    const _data = args[0].u_srkpce;
    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_srcesm.setProps({
          required: true, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_srkpce");

  useValuesChange(({ args }) => {
    console.log(`监听银行`, args);
    GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
  }, "p_form_invoice_apply_m.u_gfyh");

  useValuesChange(({ args }) => {
    console.log("监听红蓝类型", args);
    const isRed = args[0].u_hllx.value === "1"; // 蓝字为 true
    sumAmt()

    
    $NG.updateUI((updater) => {
      updater.editbar.p_form_invoice_apply_d.imp.setProps({
        disabled:!isRed
      })
    });
    hiddenKey()
  }, "p_form_invoice_apply_m.u_hllx");
  if (page.oType == "add" || page.oType == "edit") {
    let _xfyh = null;
    const _xfTime = setInterval(() => {
      try {
        if (mstform.getItem("u_xfyh").getValue() !== _xfyh) {
          _xfyh = mstform.getItem("u_xfyh").getValue();
          GetBankInfoByPhid(mstform.getItem("u_xfyh").getValue(), "xf");
        }
      } catch (err) {
        clearInterval(_xfTime);
        console.log("自定义监听器报错，行号：102");
      }
    }, 1000);

    let _gfyh = null;
    const _gfTime = setInterval(() => {
      try {
        if (mstform.getItem("u_gfyh").getValue() !== _gfyh) {
          _gfyh = mstform.getItem("u_gfyh").getValue();
          GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
        }
      } catch (err) {
        clearInterval(_gfTime);
        console.log("自定义监听器报错，行号：115");
      }
    }, 1000);
  }

  //p_form_invoice_apply_d

  
  ///////////////////////
  useUpdateRows(({ args }) => {
    const _data = args[0];
    // 分流操作，防止并发太多
    if (d1RowsLock) {
      clearTimeout(d1RowsLock);
    }
    d1RowsLock = setTimeout(() => {
      sumAmt();
      // 获取项目
    }, 600);
    // 默认数量为1
    // args[0].forEach((item) => {
    //   if (!item.qty || item.qty < 0) {
    //     item.qty = 1;
    //   }
    // });

    // 遍历明细，如果明细存在建筑服务的税收分类编码，更改主表字段属性

    const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz"];
    let isRequired = false;
    let filter = "itm3_tax_classcode.phid != 0"; // 默认值

    // _data.forEach(async (item) => {
    //   await getSumEqInfo(mstform, item);
      
    //   dgrid.refreshView();
    // });

    _data.forEach((item) => {
    //   if (item.u_ssfl_no == 4100 && mstform.getItem("u_hllx").getValue() == '1') {
    //     isRequired = true;
    //   }
      if(!item.u_kp_remark){
        item.u_kp_remark = '无'
      }
    });

    isGcService()

    
    // $NG.updateUI((updater) => {
    //   fields.forEach((field) => {
    //     updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
    //       required: isRequired,
    //       hidden: !isRequired,
    //     });
    //   });
    // });
    hiddenKey()
    if (!mstform.getItem("u_tdyw").getValue()) {
      mstform.getItem("u_tdyw").setValue({
        value: "E03",
        label: "建筑服务",
      });
    }

    dgrid.refreshView();
  }, "p_form_invoice_apply_d");

  //判断是否是工程服务
  function isGcService(){
    const _data = dgrid.getRows()
    if (_data.some((item) => item.u_ssfl_no == 4100)) {
        _data.forEach((el)=>{
            if(el.u_ssfl_no != 4100){
                el.u_ssfl_no = undefined
                el.u_ssfl_no_EXName = undefined
            }
        })        
      filter = "itm3_tax_classcode.phid = 4100";
    } else {
        filter = "1=1";
    }
    $NG.updateUI((updater) => {
        const ssflField = updater.editGrid.p_form_invoice_apply_d.u_ssfl_no;
        if (ssflField) {
          ssflField.setProps({ clientSqlFilter: filter });
        }
      });
  }

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听 u_cnt_no`);
    await getCntDInfoByPhid(mstform, args[0]);
    // await getSumEqInfo(mstform, args[0]); // 等 getCntDInfoByPhid 执行完成之后再执行
    instance.updateRow(args[0]);
  }, "p_form_invoice_apply_d.u_cnt_no");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听税收分类编码`);
    // console.log(`args`, args);
    
    getItm3TaxClasscode(args[0])
    
  }, "p_form_invoice_apply_d.u_ssfl_no");

  useDataIndexChange(async ({ args, instance }) => {

    isItno(args[0],true)
    getItm3TaxClasscode(args[0])
    instance.updateRow(args[0]); // 更新界面
  }, "p_form_invoice_apply_d.taxrate");
  function isItno(row,init = false){
    
    console.log(`税率测试`,row);

    if(!init){
      if(row.u_ssfl_no){
        return 
      }
    }
    switch(Number(row.taxrate)){
        case 0.13:
        case 0.16:
        case 0.17:
            row.u_ssfl_no = 3499
            row.u_ssfl_no_EXName = "1090513010000000000"
            row.u_ssfl_name = null
            break
        case 0.06:
            row.u_ssfl_no = 3964
            row.u_ssfl_no_EXName = "3040201990000000000"
            row.u_ssfl_name = null
            break
        case 0.09:
            row.u_ssfl_no = 4100
            row.u_ssfl_no_EXName = "3050100000000000000"
            row.u_ssfl_name = null
            break 
        default :
            row.u_ssfl_no = null
            row.u_ssfl_no_EXName = null
            row.u_ssfl_name = null
    }
  }
  // 税收分类编码
  function getItm3TaxClasscode(row){
    $NG.execServer("getItm3TaxClasscode", { phid: row.u_ssfl_no }, function (res) {
        // console.log(res);
        if (res.count > 0) {
          const data = JSON.parse(res.data)[0].extendObjects; //单返回值
          // console.log(data);
          row.u_ssfl_name = data.class_name;
          row.u_ssfljc = data.class_spjm;
          row.u_yhzc = data.preferential;
          row.u_yhzclx = data.preferential_type;
          if (row.u_ssfl_no === 4100) {
            row.u_pc_zs = 23;
            row.u_pc_zs_EXName = "9%税率的服务、不动产和无形资产";
          }
          dgrid.refreshView()
        } else {
          console.log("getItm3TaxClasscode 功能扩展暂无数据");
        }
      });
  }

  //根据合同id获取合同信息
  async function getCntMInfoByPhid(params) {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      //帮助字段赋值
      console.log(`开票税率`,datas.invoice_type_name.match(/.*(\d+)%.*/)?Number(datas.invoice_type_name.match(/.*(\d+)%.*/)[1])/100:null);
      $NG.updateState((updater) => {
        console.log("获取合同数据", datas);
        updater.data.p_form_invoice_apply_m.setProps({
          u_cnt_amt: datas.cnt_sum_vat_fc,
          u_cnt_no: datas.pcm_no,
          //购方信息（客户信息）（收票单位信息）
          u_gfmc: {
            //单位名称
            value: datas.tick_id,
            label: datas.tick_name,
          },
          u_gfbm: datas.tick_no, //单位编码
          u_gfsh: datas.tick_unisocialcredit, //社会信用代码
          u_gfdz: datas.tick_taxaddress, //单位地址
          u_gfdh: datas.tick_taxtelephone, //联系电话
          u_gfyh: {
            //银行名称
            value: datas.tick_taxbankid,
            label: datas.tick_taxbankname,
          },
          u_gfyhzh: datas.tick_taxaccountno, //银行账号
          //销方信息（供应商信息）（开票单位信息）
          u_xfmc: {
            //单位名称
            value: datas.inv_id,
            label: datas.inv_name,
          },
          inv_no: datas.inv_no, //单位编码
          u_xfsh: datas.inv_unisocialcredit, //社会信用代码
          u_xfdz: datas.inv_taxaddress, //单位地址
          u_xfdh: datas.inv_taxtelephone, //联系电话
          u_xfyh: {
            //银行名称
            value: datas.inv_taxbankid,
            label: datas.inv_taxbankname,
          },
          u_xfyhzh: datas.inv_taxaccountno, //银行账号
          phid_fcur: {
            value: datas.phid_fcur,
            label: datas.phid_fcur_name,
          },
          exchangerate: datas.exch_rate,
          u_kpsl:datas.invoice_type_name.match(/.*?(\d+)%.*/)?Number(datas.invoice_type_name.match(/.*?(\d+)%.*/)[1])/100:null
        });
      });
    });
  }
  // 通过项目过滤合同号 初始化
  function cntMFilter() {
    if (!mstform) return;
    console.log(`正在过滤`);
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_invoice_apply_m.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
          console.log(`项目名：`, phid_pc);
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1, //合同类型
            phid_pc: $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }
  // getLzfpInfo
  page.oType == 'add' && getLzfpInfo()
  function getLzfpInfo(){
    const fphm = mstform.getItem("u_lzfphm").getText()
    if(!fphm) return
    $NG.execServer("getLzfpInfo",{fphm},(res)=>{
      if(res.count == 0) return
      const _temp = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater)=>{
        updater.data.p_form_invoice_apply_m.setProps({
            u_invoice_type:{
                value:_temp.u_invoice_type,
                label:_temp.u_invoice_type_exname
            }
        })
      })
      const _data = JSON.parse(res.data).reduce((value,item)=>{
        delete item.u_invoice_type
        delete item.u_invoice_type_exname
        for(let key in item.extendObjects){
          if(key.includes("exname")){
            let temp = key.replace("exname","EXName")
            item.extendObjects[temp] = item.extendObjects[key]
            delete item.extendObjects[key]
          }
          item.extendObjects.prc = -(Number(item.extendObjects.prc) || 0)
        }
        value.push(item.extendObjects)
        return value
      },[])
      dgrid.clearRows().then(()=>{
        dgrid.addRows(_data)
      })
    })
  }
  async function getCntCount() {
    if (!mstform) return;
    console.log(`正在获取合同数量`);
    const phid = mstform.getItem("phid_pc").getValue();
    if (!phid) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: phid }, function (res) {
      console.log(res);
      if (res.count !== 0) {
        const _datas = JSON.parse(res.data);
        if (_datas.length === 1) {
          const _data = _datas[0].extendObjects;
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_cnt: {
                label: _data.bill_name,
                value: _data.phid,
              },
            });
            setTimeout(() => {
              cntDFilter();
              if (page.oType == "add") {
                getCntMInfoByPhid();
                getKpinfoTotalAmt()
                getXsCntskInfo()
                getProjectInAmtInfo()
              }
            }, 200);
          });
        }
      }
    });
  }

  //计算本次申请含税/未税金额表头
  function sumAmt() {
    if(page.oType == 'view') return 
    const _arr = dgrid.getRows();
    let _count = 0;
    let _count_vat = 0;
    _arr.forEach((item) => {
        isItno(item)
        if(!item.u_ssfl_no || !item.u_ssfl_name){
            getItm3TaxClasscode(item)
        }
      // 计算逻辑
      item.amt = item.prc * item.qty
      item.u_vat_prc = item.prc * (1 + (Number(item.taxrate) || 0))
      item.u_jshj = item.u_vat_prc * item.qty
      item.u_ratee = item.u_jshj - item.amt
      // 累计含税
      let current = window._catch_total_kpamt.filter((it)=>{
        if(it.u_cnt_no == item.u_cnt_no){
            return it
        }
      })
      console.log(`匹配到的元素`,current);
      if(current.length != 0 ){
        item.u_total_inv_amt_vat = (Number(item.u_jshj) || 0) + (Number(current[0].amt_vat)||0)
        item.u_total_inv_amt = (Number(item.amt) || 0) + (Number(current[0].amt)||0)
        
      } else {
        item.u_total_inv_amt_vat =  item.u_jshj
        item.u_total_inv_amt = item.amt
      }
      _count += Number(item.amt) || 0;
      _count_vat += Number(item.u_jshj) || 0;
      if(item.u_total_inv_amt_vat > item.u_hthj){
        $NG.alert("累计含税（含本次）不能超过价税合计！")
        item.qty = 0
        item.u_ratee = 0
        item.amt = 0
        item.u_jshj = item.u_vat_prc * item.qty
    }
    });
    console.log(`累计金额调试`,window._catch_kpsq_totalAmtVat);
    console.log(`累计金额调试`,window._catch_kpsq_totalAmt);
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_amt_total_apply_vat: _count_vat,
        u_amt_total_apply: _count,
        u_ljkpje: window._catch_kpsq_totalAmtVat + _count_vat,
        u_ljkpjews: (Number(window._catch_kpsq_totalAmt) || 0) + (Number(_count) || 0) ,
        u_srkpce:(Number(mstform.getItem("u_yqrsr").getValue()) || 0) - (window._catch_kpsq_totalAmtVat + _count_vat),
        u_hkkpce:(Number(mstform.getItem("u_ljhkje").getValue()) || 0) - (window._catch_kpsq_totalAmtVat + _count_vat),
      });
      console.log(`错误测试`,(Number(mstform.getItem("u_ljhkje").getValue()) || 0) , window._catch_kpsq_totalAmtVat + _count_vat);
    });
    
    if(mstform.getItem("u_hllx").getValue() == '2'){
        $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
                u_ljhzfp: Math.abs(_count_vat)
            });
          });
    }
    dgrid.refreshView()
  }

  //新增部分合同详细
  //通过数量和单价计算金额
  function calculationPay() {
    const arr = ["p_form_invoice_apply_d.u_qty", "p_form_invoice_apply_d.u_vat_prc", "p_form_invoice_apply_d.v_amt"];
    arr.forEach((item, index) => {
      useDataIndexChange(({ args, instance }) => {
        console.log(`监听----${item}`, args);
        args[0].u_amt = (args[0].u_qty || 0) * args[0].u_vat_prc || 0;
        instance.updateRow(args[0]);
      }, item);
    });
  }
  // 获取银行行号
  //根据银行主键获取银行信息
  function GetBankInfoByPhid(phid, str) {
    const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
    console.log(`检查传入的参数`, phid, str);
    if (!phid || !str) return;
    $NG.execServer("GetBankInfoByPhid", { phid: phid }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      // console.log(datas);
      if (str == "gf") {
        mstform.getItem("u_gfhh").setValue(datas.bankno);
        console.log(`购方行号：`, datas.bankno);
      } else if (str == "xf") {
        mstform.getItem("u_xfhh").setValue(datas.bankno);
      }
    });
  }
  function sumAmountBeforeDate(dataList, targetDateStr) {
    const targetDate = new Date(targetDateStr);
  
    return dataList.reduce((sum, item) => {
      const itemDate = new Date(item.u_receivable_dt);
      if (itemDate <= targetDate) {
        return sum + Number(item.u_payable_amt);
      }
      return sum;
    }, 0);
  }
  // 获取开票申请的累计金额
  getKpinfoTotalAmt()
  function getKpinfoTotalAmt(){
    const cnt = mstform.getItem("u_cnt").getValue()
    if(!cnt) return
    $NG.execServer("getKpinfoTotalAmt",{cnt},(res)=>{
        console.log('获取累计值',res);
        
        if(res.count == 0) {
            $NG.updateState((updater)=>{
                updater.data.p_form_invoice_apply_m.setProps({
                    u_ljkpje:0
                })
            })
            return
        }
        const _data = JSON.parse(res.data)[0].extendObjects
        window._catch_kpsq_totalAmtVat = _data.total_amt_vat - (Number(_data.total_ljhzfp_amt) || 0)
        window._catch_kpsq_totalAmt = _data.total_amt- (Number(_data.total_ljhzfp_amt) || 0)
        console.log(`累计计算`,_data.total_amt);
        window._catch_kpinfo_amt={..._data}
        setTimeout(()=>{
          sumAmt()
        },500)
    })
  }
  //获取 里程碑计划回款明细金额
  getLcbHkInfo()
  async function getLcbHkInfo(){
    const phid_pc = mstform.getItem("phid_pc").getValue();
    if(!phid_pc){return;}
    await $NG.execServer("getLcbHkInfo",{phid_pc},(res)=>{
        console.log(`里程碑计划`,res);
        if(res.count == 0) return 
        const _data = JSON.parse(res.data).reduce((value,item)=>{
            value.push({...item.extendObjects})
            return value
        },[])
        $NG.updateState((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_yskje:sumAmountBeforeDate(_data)
            })
        })
    })
  }

  // 获取销售合同收款累计金额
  getXsCntskInfo()
function getXsCntskInfo(){
    const cnt = mstform.getItem("u_cnt").getValue()
    if(!cnt) return
    $NG.execServer("getXsCntskInfo",{cnt},(res)=>{
        console.log(`销售收款`,res);
        
        if(res.count == 0)  return
        const _data = JSON.parse(res.data)[0].extendObjects
        $NG.updateState((updater)=>{
          console.log(`调试debug获取回款`,_data.total_amt,mstform.getItem("u_ljkpje").getValue());
          updater.data.p_form_invoice_apply_m.setProps({
              u_ljhkje:_data.total_amt,
          })
      })
        setTimeout(()=>{
            sumAmt()
        },200)
    })
}
// 获取累计收入报验的收入报验含税金额
getProjectInAmtInfo()
function getProjectInAmtInfo(){
    const cnt = mstform.getItem("u_cnt").getValue()
    if(!cnt) return
    $NG.execServer("getProjectInAmtInfo",{cnt},(res)=>{
        console.log(`收入报验`,res);
        if(res.count == 0)  return
        const _data = JSON.parse(res.data)[0].extendObjects
        $NG.updateState((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_yqrsr:_data.total_amt_vat,
                u_yqrsrws:_data.total_amt,
            })
        })
        setTimeout(()=>{
          sumAmt()
        },200)
    })
}
  // 格式化日期
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      case "yyyy-mm":
        formattedDate = `${year}-${month}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
  //按照项目和税率获取累计开票金额
async function getSumInvInfo(mstform, record) {
  console.log(`getSumInvInfo`);
  const phid = mstform.getItem("phid")?.getValue() ?? 0;
  const phid_pc = mstform.getItem("phid_pc")?.getValue();
  let data = {};
  if (!phid_pc) return;
  const res = await new Promise((resolve) => $NG.execServer("getSumInvInfo", { phid_pc: phid_pc, phid: phid }, resolve));
  if(res.count == 0){
    window._catch_total_kpamt = []
    return
  }
  window._catch_total_kpamt = JSON.parse(res.data).reduce((value,item)=>{
    const el = item.extendObjects
    value.push(el)
    return value
  },[])
  console.log(`获取明细累计`,window._catch_total_kpamt);
  setTimeout(()=>{
    sumAmt()
  },500)
}
});

// 获取项目
function getProjectInfo(mstform) {
  console.log(`getPtInfoByPhid`);
  const phid = mstform.getItem("phid_pc")?.getValue();
  if (!phid) return;
  try {
    $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
      if (res.count == 0) return;
      const _data = JSON.parse(res.data)[0].extendObjects;
      const isYesNoText = (value) => (value === "1" ? "是" : "否");
      $NG.updateState((updater) => {
        updater.data.p_form_invoice_apply_m.setProps({
          u_pc_no: _data.pc_no, //项目编码
          u_pc_no: _data.pc_no, //项目编码
          //事业部or组织
          phid_org: {
            value: _data.org_phid,
            label: _data.org_name,
          },
          phid_emp: {
            label: _data.project_manager_name,
            value: _data.project_manager_phid,
          },
          //售前顾问
          u_sqgw: {
            value: _data.user_sqgw_phid,
            label: _data.user_sqgw_name,
          },
          //区域中心
          u_regional_center: {
            value: _data.regional_center_phid,
            label: _data.regional_center_name,
          },
          //产品线
          u_product_line: {
            value: _data.midwife_phid,
            label: _data.midwife_name,
          },
          //部门
          u_dept: {
            value: _data.dept_phid,
            label: _data.dept_name,
          },
          //项目类型
          u_pc_type: {
            value: _data.type_phid,
            label: _data.type_name,
          },
          u_sfqf: { value: _data.user_sf_qf, label: isYesNoText(_data.user_sf_qf) }, // 这里将数值转换为文本描述
        });
      });
    });
  } catch (err) {
    $NG.alert("获取项目信息发生失败请检查~");
  }
}

// 获取企业信息
function getEnterpriseInfoByPhid(mstform) {
    // 禁用
    return
  console.log("getEnterpriseInfoByPhid");
  const phid_org = mstform.getItem("phid_org");
  if (!phid_org) return;

  const phidValue = phid_org.getValue();
  if (!phidValue) return console.warn("phid_org 为空，无法获取企业信息");

  $NG.execServer("getEnterpriseInfoByPhid", { phid: phidValue }, (res) => {
    if (res.count == 0) return;
    try {
      const datas = JSON.parse(res.data)[0].extendObjects;
      if (!datas) return;
      // console.log("组织信息", datas);
      $NG.updateState((updater) => {
        updater.data.p_form_invoice_apply_m.setProps({
          u_xfmc: datas.compname,
          u_xfsh: datas.unisocialcredit,
          u_xfdz: datas.taxaddress,
          u_xfdh: datas.taxtelephone,
          u_xfyhzh: datas.bankno,
          u_xfyh: datas.taxbankname,
          u_xfhh: datas.taxaccountno,
        });
      });
    } catch (error) {
      console.error("解析企业信息出错", error);
    }
  });
}
// 获取供应商信息（销房）
function searchGys(phid){
    if(!phid) return 
    $NG.execServer("searchGys",{phid},(res)=>{
        if(res.count == 0) return
        const _data = JSON.parse(res.data)[0].extendObjects
        $NG.updaterUI((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_xfsh:_data.taxaccountno,
                u_xfdz:_data.user_zc_address,
                u_xfdh:_data.taxtelephone,
                u_xfhh:_data.user_yhhh,
                u_xfyh:{
                    label:_data.taxbankname,
                    value:_data.taxbank_id
                },
                u_xfyhzh:_data.user_yhzhmc
            })
        })
    })
}




function mstformUpdateUI(mstform) {
  console.log("mstformUpdateUI");
  mstform.getItem("u_hllx").setValue({
    value: "1",
    label: "蓝字发票",
  });
}

function cntDFilter() {
  $NG.updateUI((updater) =>
    updater.editGrid.p_form_invoice_apply_d.u_cnt_no.setProps((p) => {
      return {
        ...p,
        editor: {
          ...p.editor,
          clientSqlFilter: {
            pphid: $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue() || 0,
          },
        },
      };
    })
  );
}

async function getCntDInfoByPhid(mstform, record) {
  console.log("getCntDInfoByPhid");

  try {
    const cndId = mstform.getItem("u_cnt")?.getValue();
    const phid = record.u_cnt_no;

    const res = await new Promise((resolve) => $NG.execServer("getCntDInfoByPhid", { cnd_id: cndId, phid }, resolve));

    console.log(res);

    if (res.count > 0 && res.data) {
      const parsed = JSON.parse(res.data);
      const data = parsed[0]?.extendObjects;

      if (data) {
        console.log(data);
        record.u_cnt_name = data.item_name || ""; // 合同清单编码
        record.u_ggxh = data.user_ggxh || ""; // 规格型号
        record.u_msunit = data.unit_phid || "";
        record.u_msunit_EXName = data.unit_name || ""; // 计量单位
        record.qty = data.qty || 0; // 数量
        record.taxrate = data.taxrate || 0; // 税率
        record.prc = data.prc_fc || 0; // 未税单价
        record.u_vat_prc = data.prc_vat_fc || 0; // 含税单价
        record.amt = data.amt_fc || 0; // 未税金额
        record.u_jshj = data.amt_vat_fc || 0; // 含税金额
        record.u_ratee = record.u_jshj - record.amt; // 税额
      } else {
        console.warn("extendObjects 数据为空");
      }
    } else {
      console.log("功能扩展暂无数据");
    }
  } catch (error) {
    console.error("getCntDInfoByPhid 异常：", error);
  }
}
